package ntu.metaweb.result;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import ntu.metaweb.storage.WebPageQuery;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("xmlresponse")
public class PageTags {
	@XStreamAlias("alltag")
	public HashSet<Tag> allTag;
	@XStreamAlias("usertag")
	public HashSet<Tag> userTag;
	
	public PageTags(String username, WebPageQuery webPageQuery) {
		System.out.println("in page tags constructor");
		Iterator<ntu.metaweb.storage.Tag> tags = webPageQuery.getTags();

		
		HashMap<String, Tag> tempAllSet = new HashMap<String, Tag>();
		HashMap<String, Tag> tempUserSet = new HashMap<String, Tag>();
		
		int maxRating = Integer.MIN_VALUE;
		int minRating = Integer.MAX_VALUE;
		
		while (tags.hasNext()) {
			ntu.metaweb.storage.Tag tag = tags.next();
			int rating = tag.getTotalRating() + tag.getContributors().size();
			tempAllSet.put(tag.getText(), 
					new Tag(tag.getText(), tag.getContributors().size(), 
							tag.getTotalRating(), rating));
			
			if (tag.getContributors().contains(username)) {
				tempUserSet.put(tag.getText(), tempAllSet.get(tag.getText()));
			}
			
			maxRating = maxRating > rating ? maxRating : rating;
			minRating = minRating < rating ? minRating : rating;
		}
		
		int ratingRange = maxRating - minRating;
		for (Tag t : tempAllSet.values()) {
			t.fontsize = ratingRange == 0 ? 0 : 
				Math.round((t.rating - minRating) / ratingRange * 6);
		}
		
		allTag = new HashSet<Tag>(tempAllSet.values());
		
		if (username != null) {
			userTag = new HashSet<Tag>(tempUserSet.values());
		}
	}
}
